#!/bin/bash
# - test_prefix

## mdadm is a tool for managing Linux Software RAID arrays.

cd $BENCHMARK_ROOT/mdadm-selftests || exit 1

. $LKP_SRC/lib/upload.sh
. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/reproduce-log.sh

mount_partition()
{
	[ $nr_partitions -ge 1 ] || return

	local partition=${partitions%% *}
	local mnt=/var/tmp

	local char="$(echo -n $partition | tail -c 1)"
	case $char in
	[!0-9])
		printf "n\np\n1\n\n+5G\nw\n" | fdisk $partition || return
		partition=$partition"1"
		;;
	esac

	log_cmd mkdir -p $mnt
	log_cmd mke2fs -t ext3 -b 4096 -J size=4 -q $partition || return
	log_cmd mount -t ext3 $partition $mnt || return
}

mount_partition || die "mount partition failed"

[ -n "$test_prefix" ] || die "test_prefix is emtpy"

# https://raid.wiki.kernel.org/index.php/RAID_setup
modprobe raid0
modprobe raid1
modprobe raid10
modprobe raid456

# fix: losetup: /dev/loop13: failed to use device: No such device
# the test needs 14 loop devices /dev/loopN (N: from 0 to 13)
# kconfig such as v5.1-rc4, the default value of max_loop is 8
modprobe -r loop
modprobe loop max_loop=14 || die "failed to modprobe loop"

check_ignored_cases()
{
	local casename=$1
	local ignored_by_lkp=$LKP_SRC/pkg/mdadm-selftests-addon/ignored_by_lkp

	# skip cases that in ignored_by_lkp
	[ -f "$ignored_by_lkp" ] || return
	grep -q -w $casename "$ignored_by_lkp"
}

run_test()
{
	# sub-case "01raid","07","11","19" typicall need to cost more time.
	local prefix=""
	case $test_prefix in
		19) prefix="timeout 60m"
		;;
		01raid|11) prefix="timeout 30m"
		;;
		07*) prefix="timeout 15m"
		;;
		*) prefix="timeout 5m"
		;;
	esac
	$prefix ./test "--tests=$testcase"

	[ $? -eq 124 ] && echo "$testcase TIMEOUT"

	local res_dir="result/$testcase"
	mkdir -p  $res_dir
	cp /var/tmp/log $res_dir
}

# The udev rule (/lib/udev/rules.d/64-md-raid-assembly.rules) will make sub-case "07" fail
if [ "$test_prefix" != "07" ]; then
	make install || die "make install failed"
fi

for testcase in $(cd tests && ls ${test_prefix}*); do
	check_ignored_cases $testcase && echo "${testcase}... ignored_by_lkp" && continue

	# some testcases may need to wait for the environment to get ready.
	# "make install" will install udev rules, sleep is required.
	# "run_test" could create/delete loop devices, sleep is required.
	sleep 5

	run_test
done

[ -d result ] && upload_files -t results result/*

exit 0
